package models.helpers;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import models.entities.ProductEntity;
import play.Play;

import java.security.NoSuchAlgorithmException;

public class StringHelper {
    public static boolean isNumeric(String s) {
        return java.util.regex.Pattern.matches("\\d+", s);
    }

    public static boolean isNullOrEmpty(String val) {
        return val == null || val.isEmpty();
    }

    public static String encrypt(String valueToEncrypt) throws NoSuchAlgorithmException {
        DesEncrypter encrypter = new DesEncrypter(Play.configuration.getProperty("email.image.secret"));
        return encrypter.encrypt(valueToEncrypt);
    }

    public static String decrypt(String valueToDecrypt){
        DesEncrypter encrypter = new DesEncrypter(Play.configuration.getProperty("email.image.secret"));
        return encrypter.decrypt(valueToDecrypt);
    }

    public static String encryptProduct(ProductEntity product) throws NoSuchAlgorithmException {
        Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
        String productJson = gson.toJson(product);
        String encryptedJson = encrypt(productJson);
        return encryptedJson;
    }

    public static ProductEntity decryptProduct(String encryptedProduct){
        String productJson = decrypt(encryptedProduct);
        Gson gson = new Gson();
        ProductEntity product = gson.fromJson(productJson, ProductEntity.class);
        return product;
    }

    public static String getPercentString(int current, int total) {
        Double result = ((double) current / (double) total) * 100;
        return String.format("%1$.0f", result);
    }
}
